Developer Guide
This document explains how to reuse the chat and document-grounded QA patterns from this example in other desktop apps.
Install and Set Up LM Studio
- Install LM Studio from the official website. (https://lmstudio.ai/)
- Download and load at least one local chat model. You sould do this in LM Studio. (Tested with qwen3-4b-instruct-2507)
- Start the local LM Studio server.
- Verify endpoints:
GET http://localhost:1234/v1/modelsPOST http://localhost:1234/v1/chat/completions
- Configure your app to use
BaseURL = http://127.0.0.1:1234(or your custom host/port).
For document extraction in this example, install pdftotext (PDF) and pandoc (DOCX) if you need those formats.
Core Pieces to Reuse
- API client class:
LMStudioAPI(HTTP wrapper for local model calls). - Chat orchestration: send user messages, receive completions, append to transcript.
- Continuation loop: auto-request
continuechunks for long outputs. - RAG layer: attach files, extract text, chunk/index, retrieve, augment prompt.
LMStudioAPI Integration Contract
Instantiate one API client and set at minimum:
BaseURL(default:http://127.0.0.1:1234)Model(set from available models)MaxTokens,PerRequestMaxTokens,Temperature,TopPMemory = Truefor continuation-based long outputs
Handle events:
ResponseReceived("available.models", data)ResponseReceived("chat.completion", messages)ErrorReceived(url, status, content)
Chat Flow
onUserSend(message):
setWorking(true)
add user line to transcript
outbound = buildPrompt(message) // plain chat or RAG-augmented
api.AddMessage("user", outbound)
api.SendChatCompletionRequest()
onChatCompletion(reply, finishReason):
append assistant chunk
if shouldContinue(finishReason, chunkSize):
api.AddMessage("user", "Continue exactly where you left off...")
api.SendChatCompletionRequest()
else:
close assistant block
setWorking(false)
Keep a hard max continuation count to avoid runaway loops.
RAG Pipeline
- Collect user-selected files.
- Enforce limits (example: max 5 files, max 30MB total).
- Extract text by extension.
- Chunk text with overlap (example: 1200 chars, 200 overlap).
- Store
chunks[]and matchingsources[]. - At query time, score chunks against question terms.
- Inject top chunks into prompt.
outbound =
"Use retrieved excerpts to answer. If missing, say not found." +
"\n\nQuestion:\n" + question +
"\n\nRetrieved Excerpts:\n" + topChunksText
Recommended retrieval safety checks:
- Always bounds-check parallel arrays (
chunks/sources). - Skip empty chunks.
- Return gracefully when no matches are found.
File Extraction Strategy
.txt/.csv: direct file read..pdf: externalpdftotext..docx: externalpandoc.
If external tools are unavailable, skip file with a clear warning and keep app responsive.
Porting Checklist
- Copy the API client class and expose model settings in your UI.
- Wire completion/error events to your transcript view.
- Add a
setWorking(true/false)path around request lifecycle. - Add continuation guardrails (
max continuations+ final stop conditions). - Implement attach/index/retrieve functions and prompt augmentation.
- Ensure transcript always auto-scrolls on append.
Tuning Knobs
PerRequestMaxTokens: lower for faster chunk turnaround.kAutoContinueMax: higher for longer aggregate outputs.kTopChunks: increase for broader context, decrease for tighter grounding.kChunkChars/kChunkOverlapChars: tune retrieval granularity.kLikelyTruncatedChars: fallback continuation heuristic threshold.
Failure Handling Recommendations
- Never crash on missing keys in JSON responses.
- Catch and report extraction/indexing errors per file.
- Turn off busy indicator in every terminal path (success, capped continuation, error).
- Log server URL/status/body on request failures for diagnostics.